/**
 * Copyright (c) 2019-2021,  陈俊兵 (cjb6b.com@gmail.com)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ktjiaoyu.advance.deadlock;

/**
 *
 * @packageName com.ktjiaoyu.mianshi.thread.dead
 * @fileName LeftRightDeadLock.java
 * @author 陈俊兵 (cjb6b.com@gmail.com)
 * @createTime 2020/9/27 16:59
 * @lastModify 2020/9/27 16:59
 * @version 1.0.0
 */
public class LeftRightDeadLock {

    public static void main(String[] args) {
        Object left = new Object(); //
        Object right = new Object();
        Thread t1 = new Thread(()->{
            synchronized (left){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "获得left锁！");
                System.out.println(Thread.currentThread().getName() + "准备获取right锁！");
                synchronized (right){
                    System.out.println(Thread.currentThread().getName() + "获得right锁！");
                }
                System.out.println(Thread.currentThread().getName() + "释放了right锁！");
            }
            System.out.println(Thread.currentThread().getName() + "释放了left锁！");
        }, "A");

        Thread t2 = new Thread(()->{
            synchronized (right){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "获得right锁！");
                System.out.println(Thread.currentThread().getName() + "准备获取left锁！");
                synchronized (left){
                    System.out.println(Thread.currentThread().getName() + "获得left锁！");
                }
                System.out.println(Thread.currentThread().getName() + "释放了left锁！");
            }
            System.out.println(Thread.currentThread().getName() + "释放了right锁！");
        }, "B");

        t1.start();
        t2.start();
    }
}
